import { PropsWithChildren } from 'react';
import {
    ProFormDatePicker,
    ProFormSelect,
    ProFormText,
    ProFormCascader,
} from '@ant-design/pro-form';
import { Row, Col } from 'antd';
import { ProColumnType } from '@ant-design/pro-table';
export type NamePath = string | number | (string | number)[];
export interface GenernalItemProps<T> extends PropsWithChildren<{}> {
    columns: ProColumnType<T>[];
    prefix?: NamePath;
}

export const joinNamePath = (prefix: NamePath | undefined, suffix: NamePath) =>
    typeof prefix !== 'undefined'
        ? ([prefix, suffix].flat(Infinity) as NamePath)
        : suffix;
export default function GenernalItem<T>(props: GenernalItemProps<T>) {
    const renderColumn = (column: ProColumnType<T>) => {
        const {
            valueType = 'text',
            fieldProps,
            key,
            dataIndex,
            valueEnum,
            initialValue,
            title,
            hideInSearch,
            formItemProps,
        } = column;

        const newValueEnum =
            Object.entries(valueEnum || {})?.map(([key, val]) => ({
                label: val,
                value: isNaN(parseInt(key)) ? key : parseInt(key),
            })) || [];

        if (hideInSearch) return null;
        let name = (key || dataIndex) as NamePath;
        const label = title;

        name = (
            typeof props.prefix !== 'undefined'
                ? [props.prefix, name].flat(Infinity)
                : name
        ) as NamePath;

        const commonProps = {
            fieldProps: {
                placeholder: '请输入' + label,
                ...fieldProps,
            },
            formItemProps: { ...formItemProps },
            label: label,
            initialValue: initialValue,
            name: name,
        };
        switch (valueType) {
            case 'text':
                return <ProFormText {...commonProps} />;
            case 'select':
                return (
                    <ProFormSelect
                        {...commonProps}
                        // @ts-ignore
                        options={newValueEnum}
                    />
                );
            case 'date':
                return <ProFormDatePicker {...commonProps} />;
            case 'cascader':
                // @ts-ignore
                return <ProFormCascader {...commonProps} />;
            default:
                return null;
        }
    };

    return (
        <Row justify="start" gutter={[50, 0]}>
            {props.columns.map((item) => {
                const el = renderColumn(item);
                return el ? <Col span={6}>{el}</Col> : undefined;
            })}
            {props.children}
        </Row>
    );
}
